package cubelabs.nexus.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.opentok.api.OpenTokSDK;
import com.opentok.api.constants.RoleConstants;
import com.opentok.exception.OpenTokException;

@Controller
public class RoomController {

	@RequestMapping(value = "/room")
	public ModelAndView roomPage(final HttpServletRequest request)
			throws Exception {
			ModelAndView mv = new ModelAndView();
			mv.setViewName("room");

			return mv;
			
		}
	
	@RequestMapping(value = "/room/{topic}")
	public ModelAndView getRoom(@PathVariable("topic") String topic)
			throws Exception {
			ModelAndView mv = new ModelAndView();
			mv.addObject("topic", topic);
			mv.setViewName("topic");

			return mv;
			
		}

	@RequestMapping(value="/room/getSession")
	public @ResponseBody String getSession( HttpServletRequest request,
			HttpServletResponse response){
		
		OpenTokSDK openTokSDK = new OpenTokSDK(21313161, "2c819ea062cc6557e618a4de655bcdce9e33d4f4");
		
			String sessionId = null;
			try {
				sessionId = openTokSDK.create_session().session_id;
			} catch (OpenTokException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		
		return sessionId;
	}
	
	@RequestMapping(value="/room/getToken")
	public @ResponseBody String getToken(@RequestParam("session_id") String sessionId, HttpServletRequest request,
			HttpServletResponse response){
		
		OpenTokSDK openTokSDK = new OpenTokSDK(21313161, "2c819ea062cc6557e618a4de655bcdce9e33d4f4");
		String token = null;
			try {
				token = openTokSDK.generate_token(sessionId, RoleConstants.PUBLISHER);
			} catch (OpenTokException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		
		return token;
	}

}
